package cn.edu.lcu.cs.javateaching.net;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class NetAnalyser {
	public static void main(String[] args) {
		// 1.创建容器窗体
		JFrame jf = new JFrame("NetAnalyser V1.0");
		// 2.设置窗体的布局
		jf.setLayout(new GridLayout(1, 3));
		jf.setBounds(100, 100, 900, 400);
		if (Integer.parseInt(args[0]) < 10 || Integer.parseInt(args[0]) > 20) {
			jf.dispose();
			JOptionPane.showMessageDialog(null, "Your message is wrong,please input a number between 10 and 20.");
		} else {
			probesNo = Integer.parseInt(args[0]);
			creatAndShow(jf, probesNo);
		}
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jf.setVisible(true);
	}

	public static void creatAndShow(JFrame jf, int probesNo) {

		// 1.创建面板组件和设计布局
		JPanel panel1 = new JPanel();
		panel1.setLayout(null);
		
		JPanel panel2 = new JPanel();
		JPanel panel3 = new JPanel();
		panel1.setBorder(BorderFactory.createLineBorder(Color.red, 3));
		panel2.setBorder(null);
		panel3.setBorder(null);

		// 2.创建提示标签
		JLabel label1 = new JLabel("Enter Test URL&no.of.probes and click on Process" + "\r\n");
		JLabel label2 = new JLabel("Test URL");
		JLabel label3 = new JLabel("No.of probes");
		JLabel label4 = new JLabel("Histogram");
		// 3.创建文本框
		JTextField text = new JTextField(20);
		// 3.1 为文本框创建监听事件
		text.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

			}

		});
		// 4.创建下拉框组件
		JComboBox<String> box = new JComboBox<String>();
		// 4.1 向下拉框中添加选项
		for (int i = 1; i <= probesNo; i++)
			box.addItem(getString(i));
		// 4.2为下拉框注册监听
		box.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

			}

		});

		// 5.创建文本栏
		JTextArea showArea = new JTextArea(19, 28);// 创建聊天记录的JTextArea,12行,25列
		showArea.setEditable(false);// 设置为不可编辑
		JScrollPane jScrollPane = new JScrollPane(showArea);

		JTextArea showArea2 = new JTextArea(18, 25);// 创建聊天记录的JTextArea,12行,25列
		showArea.setEditable(false);// 设置为不可编辑
		JScrollPane jScrollPane2 = new JScrollPane(showArea2);

		// 6.创建按钮
		JButton btn = new JButton("Process");
		// 6.1为按钮创建监听事件
		btn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {

				showArea.setText(null);
				showArea2.setText(null);
				String content = text.getText();
				String number = (String) box.getSelectedItem();
				// showArea.append(content);
				// showArea.append((String) number);
				String his;
				try {
					cheakURL(content, jf);
					his = PingandHistogram(content, number, showArea, jf);
					showArea2.append(his);
				} catch (FileNotFoundException e1) {

					e1.printStackTrace();
				}

			}

		});

		// 7.将组件加入到面板中

		// label1.setBounds(x, y, width, height);
		panel1.add(label1);
		panel1.add(label2);
		label2.setPreferredSize(new Dimension(60, 70));
		label2.setBounds(30, 30, 50, 20);

		// text.setBounds(x, y, width, height);
		panel1.add(text);
		// label3.setBounds(100, 100, 50, 50);
		panel1.add(label3);
		// 设置下拉框的尺寸和布局
		panel1.add(box);
		box.setPreferredSize(new Dimension(60, 30));
		box.setBounds(30, 30, 30, 30);

		// 设置按钮的尺寸和布局
		panel1.add(btn);
		btn.setPreferredSize(new Dimension(100, 30));
		btn.setBounds(12, 12, 80, 80);

		panel2.add(jScrollPane);
		panel3.add(label4);
		panel3.add(jScrollPane2);

		// 将面板组件放到容器中

		jf.add(panel1);
		jf.add(panel2);
		jf.add(panel3);

	}

	private static String getString(int i) {
		String a = i + "";
		return a;
	}

	public static String data(int min, int max, int binsize, int num[], int t) {
		int n1 = 0, n2 = 0, n3 = 0;// 记录个数

		for (int j = 0; j < t; j++) {
			if (num[j] < min + binsize) {
				n1++;
			}
			if (min + binsize <= num[j] && num[j] < (max - binsize)) {
				n2++;
			}
			if (num[j] <= max && num[j] >= (max - binsize)) {
				n3++;
			}
		}

		StringBuilder builder = new StringBuilder();
		builder.append(min + "<=RTT<" + (min + binsize) + "    ");
		for (int j = 0; j < n1; j++) {
			builder.append("x    ");
		}
		builder.append("\n\n");
		builder.append((min + binsize) + "<=RTT<" + (max - binsize) + "    ");
		for (int j = 0; j < n2; j++) {
			builder.append("x    ");
		}
		builder.append("\n\n");
		builder.append((max - binsize) + "<=RTT<=" + max + "    ");
		for (int j = 0; j < n3; j++) {
			builder.append("x    ");
		}
		builder.append("\n");

		return builder.toString();

	}

	public static String PingandHistogram(String content, String number, JTextArea showArea, JFrame jf)
			throws FileNotFoundException {
		int[] num = new int[20];// 开辟一个整形数组存数据
		int probeNo = 0;// 用于计数
		int min = 0, max = 0;// 用于存放最大最小值
		int binsize = 0;
		String his = "";

		try {
			Process p = Runtime.getRuntime().exec("cmd /c ping -n " + number + " " + content);
			p.waitFor();

			try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream(), "gbk"))) {
				if ((reader.readLine()) == null) {
					jf.dispose();
					JOptionPane.showMessageDialog(null, "The ping output results in an error,please try again.");
				}
				String line = null;
				while ((line = reader.readLine()) != null) {
					showArea.append(line + "\r\n");
					if (line.contains("时间") && line.contains("ms")) {// 判断str中是否有time子串
						int first = line.indexOf("时间");// 取得子串的初始位置
						int last = line.indexOf("ms");
						String strNext = line.substring(first + 3, last);// 根据的要取的内属容后多少字符+多少个
						num[probeNo] = Integer.parseInt(strNext);//
						System.out.println(num[probeNo]);
						probeNo++;
					}
					if (line.contains("最短 =")) {
						int first = line.indexOf("最短 =");// 取得子串的初始位置
						int last = line.indexOf("ms");
						min = Integer.parseInt(line.substring(first + 5, last));
						System.out.println("最短" + min);
					}
					if (line.contains("最长 =")) {
						int first = line.indexOf("最长 = ");// 取得子串的初始位置
						int last = line.indexOf("平均");
						max = Integer.parseInt(line.substring(first + 5, last - 3));
						System.out.println("最长" + max);
					}

				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (IOException | InterruptedException e1) {
			e1.printStackTrace();
		}
		if (max - min < 3) {
			binsize = 1;
			max = min + 3;
		} else {
			binsize = (max - min) / 3;
		} // 算出binsize
		his = data(min, max, binsize, num, probeNo);
		Fileshow(min, max, binsize, num, probeNo, content);
		return his;

	}

	public static void Fileshow(int min, int max, int binsize, int num[], int t, String content)
			throws FileNotFoundException {
		int n1 = 0, n2 = 0, n3 = 0;// 记录个数

		for (int j = 0; j < t; j++) {
			if (num[j] < min + binsize) {
				n1++;
			}
			if (min + binsize <= num[j] && num[j] < (max - binsize)) {
				n2++;
			}
			if (num[j] <= max && num[j] >= (max - binsize)) {
				n3++;
			}
		}
		Date nowTime = new Date();// 获取当前时间
		String pattern = "yyyy-MM-dd-HH-mm-ss";
		SimpleDateFormat SDF = new SimpleDateFormat(pattern);
		String timePattern = SDF.format(nowTime);// 按格式获取当前时间
		content.replace(".", "-");
		String fileName = content + "-" + timePattern + "Notepad";
		String title = content + "-" + timePattern + ".txt";
		try {
			FileOutputStream file = new FileOutputStream(fileName);
			file.write(title.getBytes());
			file.write("\n\n".getBytes());
			file.write(("RTT(ms) histogram" + "\n").getBytes());
			file.write(((min) + "-" + (min + binsize) + ":" + n1 + "\n").getBytes());
			file.write(((min + binsize) + "-" + (max - binsize) + ":" + n2 + "\n").getBytes());
			file.write(((max - binsize) + "-" + (max) + ":" + n3 + "\n").getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static int probesNo;// 静态变量，记录输入的指针数

	public static void cheakURL(String content, JFrame jf) {
		if (content == "" || (!content.contains("."))) {
			jf.dispose();
			JOptionPane.showMessageDialog(null, "The input URL is invalid,please input again");
		}
	}

//public static void cheakPing(String)

}
